const fecha = require('element-ui/lib/utils/date')

const WEEK = ['日', '一', '二', '三', '四', '五', '六']
const NO_DATE = '---'
/**
 * 日期转字符串
 *
 * @param {any} date
 * @param {string} [formatStr='yyyyMMdd']
 * @returns
 */
export const date2Str = (date, formatStr = 'yyyyMMdd') => {
  const orgDate = date
  if (!date) {
    return NO_DATE
  }
  if (!(date instanceof Date)) {
    if ((typeof date === 'string') && date.length === 8) {
      date = str2Date(date)
    } else {
      date = new Date(date)
    }
  }
  if (date.toString() === 'Invalid Date') {
    return orgDate
  }
  const fullYear = date.getFullYear()
  const year = date.getYear()
  const month = date.getMonth() + 1
  const day = date.getDay()
  const dt = date.getDate()
  const hours = date.getHours()
  const minutes = date.getMinutes()
  const seconds = date.getSeconds()
  formatStr = formatStr
    .replace(/yyyy|YYYY/, fullYear)
    .replace(/yy|YY/, year > 9 ? (year % 100).toString() : `0${year}`)
    .replace(/MM/, month > 9 ? month.toString() : `0${month}`)
    .replace(/M/g, month)
    .replace(/w|W/g, WEEK[day])
    .replace(/dd|DD/, dt > 9 ? dt.toString() : `0${dt}`)
    .replace(/d|D/g, dt)
    .replace(/hh|HH/, hours > 9 ? hours.toString() : `0${hours}`)
    .replace(/h|H/g, hours)
    .replace(/mm/, minutes > 9 ? minutes.toString() : `0${minutes}`)
    .replace(/m/g, minutes)
    .replace(/ss|SS/, seconds > 9 ? seconds.toString() : `0${seconds}`)
    .replace(/sss|SSS/, date.getTime().toString().split('').slice(-3).join(''))
  return formatStr
}

/**
 * 字符串转日期
 * @param date 字符串格式的日期
 * @param format 格式
 */
export const str2Date = (date, format = 'yyyyMMdd') => {
  if (!date || date === '') {
    return null
  }
  if (date instanceof Date) {
    return date
  }
  // fecha.format可以将日期转为字符串
  return fecha.parse(date, format)
}

/**
 * 获取当前时间字符串
 *
 * @param {string} [formatStr='yyyy/MM/dd hh:mm:ss']
 * @returns
 */
export const getTimestamp = (formatStr = 'yyyy/MM/dd hh:mm:ss') => date2Str(new Date(), formatStr)

/**
 * 获取当前日期字符串
 *
 * @param {string} [formatStr='yyyyMMdd']
 * @returns
 */
export const getDate = (formatStr = 'yyyyMMdd') => date2Str(new Date(), formatStr)

// YYYYMMDD hh:mm:ss
export const getNowTime = () => {
  const dt = new Date()
  dt.setMinutes(dt.getMinutes() - dt.getTimezoneOffset())
  return dt
    .toISOString()
    .replace(/[-]/g, '')
    .replace(/T/g, ' ')
    .substr(0, 17)
}

export const parseNowTime = time => time.replace(/-/g, '')

/**
 * 年月日加减
 * @oldDate 要操作的日期
 * @value 需要增加的日期值。正数为添加，负数为减少
 * @type 操作类型（Y/M/D，默认为D）
 */
export const addDate = (date, value, type = 'D') => {
  let year, month, day
  let flag = false
  if (typeof (date) === 'object') {
    flag = true
    date = date2Str(date)
  }
  year = parseInt(date.substring(0, 4), 10)
  month = parseInt(date.substring(4, 6), 10)
  day = parseInt(date.substring(6, 8), 10)
  value = parseInt(value, 10)
  if (type === 'Y') {
    year += value
  }
  if (type === 'M') {
    month += value
  }
  if (type === 'D') {
    day += value
  }

  let result
  // 如果小于28天的直接为下个月同一天
  if (day <= 28) {
    result = new Date(year, month - 1, day)
  } else {
    // 获取间隔月的最后一天
    const interValFirstDate = new Date(year, month, 1)
    const dayMS = 1000 * 60 * 60 * 24
    result = new Date(interValFirstDate.getTime() - dayMS)

    if (result.getDate() > day) {
      result.setDate(day)
    }

    if (type === 'D') {
      result.setDate(day)
    }
  }

  if (flag) {
    return result
  }
  return date2Str(result)
}

export default {
  getDate,
  getTimestamp,
  date2Str,
  str2Date,
  addDate
}
